package model

import (
	"blog2021/tools/logger"
	"errors"
	"time"

	"github.com/jinzhu/gorm"
)

type (
	Comment struct {
		gorm.Model
		PostId  string `gorm:"column:post_id"`
		Name    string `gorm:"column:name"`
		Content string `gorm:"column:content"`
	}

	LastComment struct {
		Id        uint
		PostId    string
		PostTitle string
		User      string
		Comment   string
		Time      time.Time
	}
)

func GetCommentsById(id string) []Comment {
	var comments []Comment
	if err := db.Where("post_id=?", id).Find(&comments).Limit(MaxCommentsCount).Error; err != nil {
		logger.Error("GetCommentsById ERROR, ", err)
	}
	return comments
}
func Comment2LastComment(comment Comment) (LastComment, error) {
	result := LastComment{}
	post, err := GetPostById(comment.PostId)
	if err == nil {
		result.Id = comment.ID
		result.PostId = comment.PostId
		result.PostTitle = post.Title
		result.User = comment.Name
		result.Comment = comment.Content
		result.Time = comment.CreatedAt
	}
	return result, err
}

func GetLastComments() []LastComment {
	var lastComments []LastComment
	var comments []Comment
	if err := db.Order("created_at desc").Limit(LastCommentsCount).Find(&comments).Error; err == nil {
		for _, comment := range comments {
			lastComment, err := Comment2LastComment(comment)
			if err == nil {
				lastComments = append(lastComments, lastComment)
			} else {
				logger.Error(err, comment.PostId)
			}
		}
	}
	return lastComments
}

func InsertComment(comment *Comment) error {
	var count int
	db.Model(&Comment{}).Where("post_id = ?", comment.PostId).Count(&count)
	if count >= MaxCommentsCount {
		return errors.New("评论数过多请联系管理员！")
	}

	if err := db.Save(comment).Error; err != nil {
		logger.Error(err)
		return err
	}

	return nil
}

func DeleteComment(id string) error {
	var comment Comment
	if err := db.Where("id = ?", id).First(&comment).Error; err != nil {
		logger.Error(err)
		return err
	}

	if err := db.Delete(&comment).Error; err != nil {
		logger.Error(err)
		return err
	}

	return nil
}
